package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Department;
import com.letv.whatslive.model.convert.DepartmentConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/3/3.
 */
@Repository
public class DepartmentDAO extends BaseDAO{
    private final static Logger logger = LoggerFactory.getLogger(DepartmentDAO.class);

    protected String collectionName = "department";

    @Autowired
    protected JedisDAO jedisDAO;

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public List<Department> getAllDepartmentByParams(Map<String, Object> params){
        List<Department> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Department department = DepartmentConvert.castDBObjectToDepartment(dbObject);
                result.add(department);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public Department getDepartmentById(Long id){
        BasicDBObject query = new BasicDBObject();
        Department department = new Department();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            department= DepartmentConvert.castDBObjectToDepartment(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return department;
    }
    private BasicDBObject getBasicDBObjectByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("id")));
            }
            if (params.get("name") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("name") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("name", pattern);
            }
        }
        return query;
    }
}
